<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Validate;
use app\admin\model\NoteType;
use think\Session;

class Category extends Controller
{
    // 初始化 防止用户未登录就访问页面
    public function _initialize()
    {
        if (!session('nodeList')) {
            return $this->error('您还未登录,请登录',url('admin/index/index'));
        }
    }
    // 分类列表
    public function index()
    {

        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $data = Db::name('category')->field(['id', 'cate_name'])->order('id')->paginate(10);

        return $this->fetch('category/index', [
            'data' => $data,
        ]);
    }

    // 分类添加
    public function add()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        return $this->fetch('category/addCategory');
    }


    // 添加分类处理
    public function doAdd()
    {

        $this->checkMethod('post');
        // 获取 post 数据
        $data = input('post.');
//        halt($data);
        // 验证数据
        $check = $this->validate($data, 'admin/Category');
//        halt($check);
        if (true === $check) {
            $result = Db::name('category')->data($data)->insert();
//            $result = true;

            if ($result > 0) {
                // 设置返回信息
                $list['status'] = $result;
                $list['msg'] = '添加成功';
                return json($list);
            } else {
                // 设置返回信息
                $list['status'] = $result;
                $list['msg'] = '添加失败,请检查名称是否有误';
                return json($list);
            }
        } else {
            // 设置返回信息
            $list['status'] = false;
            $list['msg'] = $check;
            return json($list);
        }
    }

    // 读取笔记类型
    public function readType($id)
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $list = Db::field('c.cate_name,n.id,n.tag_name')
            ->table(['2B_category' => 'c', '2B_note_type' => 'n'])
            ->where('c.id = ' . $id)
            ->where('n.cat_id = c.id')
            ->order('id')
            ->select();

//        halt($list);
        return $this->fetch('category/readType', [
            'data' => $list
        ]);
    }

    // 删除分类
    public function delCategory()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $this->checkMethod('delete');
        $id = Request::instance()->delete('id');
        // 获取该分类下是否有数据
        $data = Db::field('c.cate_name,n.id,n.tag_name')
            ->table(['2B_category' => 'c', '2B_note_type' => 'n'])
            ->where('c.id = ' . $id)
            ->where('n.cat_id = c.id')
            ->order('id')
            ->select();
//        halt($id);
//        $result = true;
        // 判断数据是否为空,如果为空则删除,不为空则不能删除
        if (!empty($data)) {
            $data['status'] = false;
            $data['msg'] = '不能删除该分类,该分类下有数据';
//            halt($data);
            return json($data);
        } else {
            $result = Db::name('category')->delete($id);
            if ($result) {
                $data['status'] = true;
                $data['msg'] = '成功删除';
                return json($data);
            } else {
                $data['status'] = false;
                $data['msg'] = '删除失败';
                return json($data);
            }
        }
    }


    // 笔记类型列表
    public function noteList()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $data = Db::field('c.cate_name,n.tag_name,n.id,n.cat_id')
            ->table(['2B_category' => 'c', '2B_note_type' => 'n'])
            ->where('c.id = n.cat_id')
            ->order('id')
            ->paginate(10);

        return $this->fetch('category/noteTypeList', [
            'data' => $data,
        ]);
    }

    // 笔记类型添加
    public function noteAdd()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        // 获取已有的分类
        $data = Db::name('category')->field(['id', 'cate_name'])->select();
//        halt($data);
        return $this->fetch('category/noteTypeAdd', [
            'cate' => $data
        ]);
    }

    public function typeDoAdd()
    {

        $this->checkMethod('post');
        // 获取 post 数据
        $data = input('post.');
        // 获取验证结果
//        halt($data);
        $checkResult = $this->typeCheck($data);


        // 添加
        if ($checkResult === true) {
            $result = Db::name('note_type')->data($data)->insert();
//            $result = true;
            if ($result) {
                // 设置返回信息
                $list['status'] = true;
                $list['msg'] = '添加成功';
                return json($list);
            } else {
                // 设置返回信息
                $list['status'] = $result;
                $list['msg'] = '添加失败,请检查名称是否有误';
                return json($list);
            }
        } else {
            // 设置返回结果
            $list['status'] = false;
            $list['msg'] = $checkResult;
            return json($list);
        }
    }


    // 笔记类型修改
    public function noteEdit()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $this->checkMethod('post');
        // 获取 post 数据
        $data = input('post.');
        $id = $data['id'];
        // 当前笔记类型信息
        $typeList = Db::name('note_type')->find($id);
        // 当前笔记类型的分类
        $cid = $data['cat_id'];
        // 获取已有的分类
        $cateList = Db::name('category')->field(['id', 'cate_name'])->order('id', 'asc')->select();

        $info = [
            $typeList, $cid, $cateList
        ];
//        halt($data);
        return json($info);
    }

    // 笔记类型修改处理
    public function doNoteEdit()
    {

        $this->checkMethod('put');
        // 获取put 数据
        $data = Request::instance()->put();
//        halt($data);
        // 验证数据
        $checkResult = $this->typeCheck($data);

        // 更新
        if ($checkResult === true) {
            // 但前要修改的id
            $id = $data['id'];
            $note = NoteType::get($id);
            $result = $note->allowField('id', true)->update($data);
            // 如果修改了分类
            $cate = Db::name('category')->find($data['cat_id']);
//            $result = true;
            if ($result) {
                // 设置返回信息
                $list['status'] = true;
                $list['msg'] = '修改成功';
                $list['cname'] = $cate['cate_name'];
                return json($list);
            } else {
                // 设置返回信息
                $list['status'] = $result;
                $list['msg'] = '修改失败,请检查名称是否有误';
                return json($list);
            }
        } else {
            // 设置返回结果
            $list['status'] = false;
            $list['msg'] = $checkResult;
            return json($list);
        }
//        halt($data);
    }

    // 删除笔记类型
    public function deleteType()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        $this->checkMethod('delete');
        $id = Request::instance()->delete();
//        halt($id);
        // 获取该标签下已有的笔记
        $list = Db::field('note.id,type.id,note.type')
            ->table(['2B_user_note' => 'note','2B_note_type' => 'type'])
            ->where('type.id = '. $id['id'])
            ->where('note.tags_id = type.id')
            ->select();
//        halt($list);
        if (!empty($list)) {
            $data['status'] = false;
            $data['msg'] = '不能删除该标签,该标签下笔记';
            return json($data);
        }

        // 删除
        $result = Db::name('note_type')->delete($id);
        if ($result) {
            $data['status'] = true;
            $data['msg'] = '成功删除';
            return json($data);
        } else {
            $data['status'] = false;
            $data['msg'] = '删除失败';
            return json($data);
        }
    }

    // 笔记类型添加数据验证
    protected function typeCheck($data)
    {
        // 制定规则
        $rule = [
            'tag_name' => ['require', 'min' => 2, 'max' => 6, 'chsAlpha', 'unique' => ['note_type', 'tag_name']],
            'cat_id' => ['require']
        ];

        // 信息提示
        $msg = [
            'tag_name.require' => '笔记类型名名不能为空',
            'tag_name.min' => '不能小于2位',
            'tag_name.max' => '过长,不能超过6位',
            'tag_name.chsAlpha' => '请不要填写数字',
            'tag_name.unique' => '该类型已存在,请重新输入',
            'cat_id.require' => '分类不能不为空,请选择分类',
        ];

        // 进行验证
        $validate = new Validate($rule, $msg);
        if ($validate->check($data)) {
            return true;
        } else {
            return $validate->getError();
        }
    }


    // 验证访问方式
    private function checkMethod($method)
    {
        switch ($method) {
            case 'post':
                if (!Request::instance()->isPost()) {
                    $this->redirect('',url('admin/Error/notFound'));
                    return;
                }
                break;
            case 'ajax':
                if (!Request::instance()->isAjax()) {
                    $this->redirect('',url('admin/Error/notFound'));
                    return;
                }
                break;
            case 'delete':
                if (!Request::instance()->isDelete()) {
                    $this->redirect('',url('admin/Error/notFound'));
                    return;
                }
                break;
            case 'put':
                if (!Request::instance()->isPut()) {
                    $this->redirect('',url('admin/Error/notFound'));
                    return;
                }
                break;
        }
    }

    /*
     * 判断权限
     */
    public function judge($auth)
    {
        $nodeList = Session::get('nodeList');
        if (empty($nodeList)) {
            return $this->error('您的权限不足!');
        }
        if (!in_array($auth,$nodeList)) {
            return $this->error('您的权限不足!');
        }
    }
}
